package com.zyx.nettypro.netty.sticky.solver;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/24 10:03
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private final AtomicInteger count = new AtomicInteger();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        //接收到数据，并处理
        int len = msg.getLength();
        byte[] content = msg.getContent();

        System.out.println("服务器接收到信息如下");
        System.out.println("长度 = " + len);
        System.out.println("内容 = " + new String(content, CharsetUtil.UTF_8));

        System.out.println("服务器接收到消息包数量 = " + count.incrementAndGet());

        System.out.println();

        // 回复消息
        String responseStr = UUID.randomUUID().toString();
        int responseLen = responseStr.getBytes(CharsetUtil.UTF_8).length;
        byte[] responseContent = responseStr.getBytes(CharsetUtil.UTF_8);

        // 构建一个协议包
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLength(responseLen);
        messageProtocol.setContent(responseContent);

        ctx.writeAndFlush(messageProtocol);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exception =====>>>>> " + cause.getMessage());
        ctx.close();
    }

}
